<template>
  <app-content class="h-panel">
    <div class="h-panel-bar"><span class="h-panel-title">凭证列表</span></div>
    <div class="margin-right-left margin-top">
      <account-date-choose v-model="accountDate"/>
      <DropdownCustom button style="margin-left:5px;">
        <span>筛选</span>
        <div slot="content" v-width="400" v-height="325" style="padding-top: 20px">
          <Form ref="searchForm" v-width="380" mode="single" :labelWidth="100">
            <FormItem label="凭证字：">
              <Select :datas="voucherWordData" placeholder="全部" keyName="word" titleName="name" v-model="queryParam.voucherWord"></Select>
            </FormItem>
            <FormItem label="制单人：">
              <Select :datas="userList" placeholder="全部" keyName="id" titleName="userName" v-model="queryParam.createMember"></Select>
            </FormItem>
            <FormItem label="摘要：">
              <input type="text" placeholder="请输入" v-model="queryParam.summary">
            </FormItem>
            <FormItem label="备注：">
              <input type="text" placeholder="请输入 " v-model="queryParam.remark">
            </FormItem>
            <FormItem label="科目：">
              <Select :datas="voucherSelect" placeholder="全部" keyName="id" titleName="subjectFullName" v-model="queryParam.subjectId"></Select>
            </FormItem>
            <FormItem label="凭证号：" single>
              <div class="h-input-group">
                <FormItem prop="money.minData" label="起始凭证号" :show-label="false">
                  <input type="text" placeholder="起始凭证号" v-model="queryParam.voucherCodeBegin" />
                </FormItem>
                <span class="h-input-addon">至</span>
                <FormItem prop="money.maxData" label="结束凭证号" :show-label="false">
                  <input type="text" placeholder="结束凭证号" v-model="queryParam.voucherCodeEnd" />
                </FormItem>
              </div>
            </FormItem>
          </Form>
          <div class="text-center">
            <Button @click="handleReset">重置</Button>
            <Button class="h-btn-primary" style="margin-left: 20px" @click="handleSearch" :loading="loading" :style="btnStyle">查询</Button>
          </div>
        </div>
      </DropdownCustom>
      <Button @click="loadList" style="margin-left:5px">刷新</Button>
      <div class="float-right">
        <template>
          <Button :loading="loading" @click="addModal" class="h-btn-primary" :style="btnStyle">新增</Button>
          <Button :loading="loading" @click="billVoucher">业务凭证</Button>
          <Button :loading="loading" @click="audit">审核</Button>
          <Button :loading="loading" @click="cancelAudit">反审核</Button>
        </template>
        <DropdownMenu button @click="trigger" :datas="param">打印</DropdownMenu>
        <template>
          <Button :loading="loading" @click="finishingOffNo">整理断号</Button>
          <Button :loading="loading" @click="batchDelete">批量删除</Button>
          <Button :loading="loading" @click="doUpload">导入凭证</Button>
          <Button :loading="loading" @click="doDownload">导出凭证</Button>
        </template>
      </div>
    </div>
    <div class="h-panel-body">
      <table class="header" :style="headerStyle">
        <tr>
          <th style="width: 50px; text-align: center"><input :checked="checkAll" type="checkbox" @click="checkAll=!checkAll"></th>
          <td style="width: 215px">摘要</td>
          <td>科目</td>
          <td align="right" style="width: 130px">借方金额</td>
          <td align="right" style="width: 130px">贷方金额</td>
        </tr>
      </table>
      <table v-if="!datas.length">
        <tr>
          <td colspan="5" class="text-center padding">暂无数据</td>
        </tr>
      </table>
      <table class="details" v-for="data in datas" :key="data.id">
        <tr class="details-header">
          <th style="width: 50px; text-align: center"><input :class="{'display':data._checked}" v-model="data._checked" type="checkbox"></th>
          <td colspan="2">日期：{{data.voucherDateStr}} 凭证字号：{{data.word}}-{{data.code}}</td>
          <td colspan="2" class="actions" align="right">
            <span v-if="data.billNo" @click="myHandleDetail(data.billNo)" :style="fontStyle">追溯</span>
            <span v-if="data.auditMemberId" @click="showModal(data.id)" :style="fontStyle">查看</span>
            <a :href="printOne(data.id)" target="_blank" :style="fontStyle">打印</a>
            <span @click="showModal(data.id)" :style="fontStyle">修改</span>
            <span @click="remove(data)" :style="fontStyle">删除</span>
            <i v-if="data.auditMemberId" class="h-icon-completed green-color" style="font-weight: bolder" v-tooltip content="已审核"></i>
          </td>
        </tr>
        <tr v-for="d in data.details" :key="d.id">
          <th></th>
          <td style="width: 215px">
            {{d.summary}}
            <template v-if="d.subject&&d.num&&d.price">
              (数量:{{d.num}}<span class="dark4-color">{{d.subject.unit}}</span>，单价:{{d.price}}<span class="dark4-color">元</span>)
            </template>
          </td>
          <td>{{d.subjectName}}</td>
          <td align="right" style="width: 130px">{{d.debitAmount|numFormat}}</td>
          <td align="right" style="width: 130px">{{d.creditAmount|numFormat}}</td>
        </tr>
        <tr class="font-bold">
          <td></td>
          <td>合计</td>
          <td>{{data.debitAmount|dxMoney}}</td>
          <td align="right">{{data.debitAmount|numFormat}}</td>
          <td align="right">{{data.creditAmount|numFormat}}</td>
        </tr>
      </table>
      <Pagination v-model="pagination" @change="currentChange" layout="pager" small align="center"/>
    </div>
    <Modal v-model="openModal" v-bind="{closeOnMask: false, hasCloseIcon: true}">
      <VoucherModal :voucherId="openModalId" ref="modalForm" @ok="modalFormOk" @close="modalFormClose"></VoucherModal>
    </Modal>
    <Modal v-model="openVoucherBill" v-bind="{closeOnMask: false, hasCloseIcon: true, hasDivider: true}">
      <div slot="header">业务凭证</div>
      <VoucherBill :voucherId="openVoucherBillId" ref="billForm" @refresh="billFormRefresh"></VoucherBill>
    </Modal>
    <Modal v-model="openImportModal" v-bind="{closeOnMask: false, hasCloseIcon: true, hasDivider: true}">
      <div slot="header">导入凭证</div>
      <Form ref="form" v-width="600" mode="single" :labelWidth="80" class="form-content">
        <FormItem label="模板：" readonly>
          <div><a href="./doc/voucher_template.xls" target="_blank"><b>Excel模板下载</b></a></div>
        </FormItem>
        <FormItem label="文件：" class="form-item">
          <Button :loading="loading" @click="handleFile" icon="h-icon-upload">
            <input ref="file" type="file" accept="application/vnd.ms-excel" style="display: none" @change="fileChange($event)">
            上传导入
          </Button>
        </FormItem>
      </Form>
    </Modal>
    <Modal v-model="openEmptyModal" v-bind="{closeOnMask: false, hasDivider: true}">
      <div slot="header">需要先创建账套才能操作</div>
      <Form ref="form" v-width="600" mode="single" :labelWidth="10" class="form-content">
        <FormItem readonly>
          <div style="font-size: 20px;">菜单路径：总账管理 > 设置 > 账套</div>
        </FormItem>
      </Form>
    </Modal>
    <!-- 表单区域 -->
    <bill-detail ref="billDetail"></bill-detail>
    <financial-detail ref="financialDetail"></financial-detail>
  </app-content>
</template>

<script>
  import Qs from "qs";
  import moment from 'moment'
  import {mapState} from 'vuex'
  import Vue from 'vue'
  import VoucherModal from './VoucherModal'
  import VoucherBill from './VoucherBill'
  import { getPrevMonthFormatDate, getFormatDate } from '@/utils/util'
  import { findBillDetailByNumber, findFinancialDetailByNumber } from '@/api/api'
  import BillDetail from '@/components/tools/BillDetail'
  import FinancialDetail from '@/components/tools/FinancialDetail'
  import { DEFAULT_COLOR } from '@/store/mutation-types'
  import { updateTheme } from '@/components/tools/setting'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'

  export default {
    name: "Voucher",
    mixins:[JeecgListMixin],
    components: {
      BillDetail,
      FinancialDetail,
      VoucherModal,
      VoucherBill
    },
    data() {
      return {
        datas: [],
        voucherSelect: [],
        openModal: false,
        openVoucherBill: false,
        openImportModal: false,
        openEmptyModal: false,
        openModalId: null,
        openVoucherBillId: null,
        accountDate: null,
        queryParam: {
          voucherWord:'',
          createMember:'',
          summary:'',
          remark:'',
          subjectId:'',
          voucherCodeBegin:'',
          voucherCodeEnd:''
        },
        pagination: {
          page: 1,
          total: 0
        },
        loading: false,
        checkAll: false,
        param: [{title: '打印全部', key: 'printAll'}, {title: '打印选中', key: 'printCheck'}],
        voucherWordData: [
          { name: '记账凭证', word: '记' },
          { name: '收款凭证', word: '收' },
          { name: '付款凭证', word: '付' },
          { name: '转账凭证', word: '转' }
        ],
        userList: [],
        disableMixinCreated: true,
        url: {
          exportXlsUrl: "/api/plugin/general-ledger/voucher/export",
        },
        headerStyle: { background: '' },
        btnStyle: { background: '', borderColor: ''},
        fontStyle: { color: ''},
      }
    },
    watch: {
      checkAll(nval) {
        let data = Array.from(this.datas);
        data.forEach(val => val._checked = nval);
        this.datas = data;
      },
      accountDate() {
        this.pagination.page = 1;
        this.loadList()
        this.loadUser()
        this.loadSubject()
      }
    },
    mounted () {
      this.primaryColor = Vue.ls.get(DEFAULT_COLOR)
      updateTheme(this.primaryColor)
      this.headerStyle.background = this.primaryColor
      this.btnStyle.background = this.primaryColor
      this.btnStyle.borderColor = this.primaryColor
      this.fontStyle.color = this.primaryColor
    },
    computed: {
      ...mapState(['User', 'currentAccountSets']),
      date() {
        return moment(this.accountDate);
      }
    },
    created () {
      this.checkAccountCount()
    },
    methods: {
      //检查是否存在账套，如果不存在就提示
      checkAccountCount() {
        this.$api.setting.accountSets.count().then(({data}) => {
          if(data === 0) {
            this.openEmptyModal = true
          } else {
            this.openEmptyModal = false
          }
        })
      },
      currentChange() {
        this.loadList();
      },
      trigger(key) {
        this[key].call(this);
      },
      printAll() {
        let param = Qs.stringify({year: this.date.year(), month: this.date.month() + 1,
          accountSetsId: this.currentAccountSets.id}, {indices: false});
        window.open(this.$api.voucher.pdfVoucher(param));
      },
      printCheck() {
        let checked = this.datas.filter(value => value._checked);
        if (checked.length) {
          let param = Qs.stringify({id: checked.map(value => value.id),
            accountSetsId: this.currentAccountSets.id}, {indices: false});
          window.open(this.$api.voucher.pdfVoucher(param));
        } else {
          this.$Message("未选择记录！");
        }
      },
      printOne(id) {
        let param = Qs.stringify({id: id, accountSetsId: this.currentAccountSets.id}, {indices: false});
        return this.$api.voucher.pdfVoucher(param)
      },
      loadList() {
        this.$api.voucher.list({year: this.date.year(), month: this.date.month() + 1, page: this.pagination.page}).then(({data}) => {
          this.datas = data.records;
          this.pagination = {
            page: data.current,
            size: data.size,
            total: data.total
          }
        })
      },
      loadUser() {
        this.$api.common.getUserList().then(({data}) => {
          this.userList = data;
        });
      },
      loadSubject() {
        this.$api.setting.subject.voucherSelect().then(({data}) => {
          this.voucherSelect = data;
        });
      },
      addModal() {
        this.openModalId = null
        this.openModal = true
      },
      showModal(id) {
        this.openModalId = id
        this.openModal = true
      },
      myHandleDetail(billNo) {
        let that = this
        this.$api.voucher.getInfoByBillNo({
          number: billNo
        }).then(({data}) => {
          let arr = data.records
          if(arr && arr.length) {
            let newType = arr[0].newType.replaceAll('零售退货', '零售退货入库').replaceAll('采购退货', '采购退货出库').replaceAll('销售退货', '销售退货入库')
            if(arr[0].fromType === 'bill') {
              findBillDetailByNumber({ number: arr[0].billNo }).then((res) => {
                if (res && res.code === 200) {
                  that.$refs.billDetail.show(res.data, newType);
                  that.$refs.billDetail.title="详情";
                }
              })
            } else if(arr[0].fromType === 'financial') {
              findFinancialDetailByNumber({ billNo: arr[0].billNo }).then((res) => {
                if (res && res.code === 200) {
                  that.$refs.financialDetail.show(res.data, newType);
                  that.$refs.financialDetail.title="详情";
                }
              })
            }
          }
        })
      },
      remove(data) {
        this.$Confirm("确认删除?").then(() => {
          this.$api.voucher.delete(data.id).then(() => {
            this.loadList();
          })
        });
      },
      finishingOffNo() {
        this.loading = true;
        this.$api.voucher.finishingOffNo({year: this.date.year(), month: this.date.month() + 1}).then(() => {
          this.loadList();
          this.$Message("整理断号成功！");
        }).finally(() => {
          this.loading = false
        });
      },
      batchDelete() {
        let checked = this.datas.filter(value => value._checked);
        if (checked.length) {
          this.$Confirm("确认删除?").then(() => {
            this.loading = true;
            this.$api.voucher.batchDelete({checked: checked.map(value => value.id), year: this.date.year(), month: this.date.month() + 1}).then(() => {
              this.loadList();
            }).finally(() => {
              this.loading = false
            });
          });
        } else {
          this.$Message("未选择记录！");
        }
      },
      billVoucher() {
        this.openVoucherBillId = null
        this.openVoucherBill = true
      },
      audit() {
        let checked = this.datas.filter(value => value._checked);
        if (checked.length) {
          this.$Confirm("亲，确认要审核吗?").then(() => {
            this.loading = true;
            this.$api.voucher.audit({checked: checked.map(value => value.id), year: this.date.year(), month: this.date.month() + 1}).then(() => {
              this.loadList();
              this.$Message("审核成功！");
            }).finally(() => {
              this.loading = false;
            });
          });
        } else {
          this.$Message("未选择记录！");
        }
      },
      cancelAudit() {
        let checked = this.datas.filter(value => value._checked);
        if (checked.length) {
          this.$Confirm("亲，确认要反审核吗?").then(() => {
            this.loading = true;
            this.$api.voucher.cancelAudit({checked: checked.map(value => value.id), year: this.date.year(), month: this.date.month() + 1}).then(() => {
              this.loadList();
              this.$Message("反审核成功！");
            }).finally(() => {
              this.loading = false;
            });
          })
        } else {
          this.$Message("未选择记录！");
        }
      },
      doUpload() {
        this.openImportModal = true
      },
      doDownload() {
        if(this.pagination.total <= 1000) {
          this.queryParam.year = this.date.year()
          this.queryParam.month = this.date.month() + 1
          this.handleExportXls('凭证')
        } else {
          this.$message.warning('抱歉，单次最多只能导出1000条，建议先进行筛选！')
        }
      },
      handleFile() {
        this.$refs.file.click()
      },
      fileChange(e) {
        if (this.$refs.file.files.length) {
          let formData = new FormData();
          formData.append('file', this.$refs.file.files[0]);
          this.loading = true;
          this.$api.voucher.import(formData).then(({data}) => {
            if (data) {
              this.accountDate = data;
            }
            this.$store.dispatch('init');
            this.$Message("亲,导入成功~");
            this.openImportModal = false
            this.loadList()
          }).finally(() => {
            this.loading = false;
          });
          this.$refs.file.value = "";
        }
      },
      modalFormOk() {
        this.loadList()
      },
      modalFormClose() {
        this.openModal = false
        this.loadList()
      },
      billFormRefresh() {
        this.loadList()
      },
      handleSearch() {
        this.$api.voucher.list({
          year: this.date.year(),
          month: this.date.month() + 1,
          page: this.pagination.page,
          voucherWord: this.queryParam.voucherWord,
          createMember: this.queryParam.createMember,
          summary: this.queryParam.summary,
          remark: this.queryParam.remark,
          subjectId: this.queryParam.subjectId,
          voucherCodeBegin: this.queryParam.voucherCodeBegin,
          voucherCodeEnd: this.queryParam.voucherCodeEnd
        }).then(({data}) => {
          this.datas = data.records;
          this.pagination = {
            page: data.current,
            size: data.size,
            total: data.total
          }
        })
      },
      handleReset() {
        this.queryParam = {
          voucherWord:'',
          createMember:'',
          summary:'',
          remark:'',
          subjectId:'',
          voucherCodeBegin:'',
          voucherCodeEnd:''
        }
        this.loadList()
      }
    }
  }
</script>

<style lang='less' scoped>
  .h-panel-bar {
    padding: 10px 20px;
  }
  .h-form .h-form-item {
    padding-bottom: 10px;
  }
  .h-panel-body {
    padding: 20px;
    table {
      width: 100%;
      border-collapse: collapse;

      td {
        padding: 7px;
      }

      &.header {
        background-color: @primary-color;
        color: white;
      }
    }

    .details {
      font-size: 12px;
      margin: 15px 0;
      border: 1px solid @gray2-color;

      .actions {
        text-align: right;
        padding-right: 20px;

        span, a {
          display: none;
        }
      }

      input {
        display: none;

        &.display {
          display: inline-block;
        }
      }

      &-header {
        background-color: @gray3-color;
        color: @dark3-color;
      }

      td, th {
        border-bottom: 1px solid @gray2-color;
      }

      tr:hover:not(.details-header) {
        background-color: #dff7df;
        cursor: pointer;
      }

      &:hover {
        box-shadow: 0 0 10px 0 #dadada;
        border-color: #dadada;

        .actions {
          span, a {
            display: inline-block;
          }
        }

        input {
          display: inline-block;
        }
      }
    }
  }

  .form-content {
    padding: 40px;
  }
  .form-item {
    padding-top: 30px;
  }
</style>
<style lang='less'>
  .h-page-pager-container .h-page-pager-selected {
    background-color: gray !important;
  }
</style>